package com.qfedu.fmmall.apiuserlogin.service.impl;


import com.fasterxml.jackson.databind.ObjectMapper;
import com.qfedu.fmmall.apiuserlogin.service.UserLoginService;
import com.qfedu.fmmall.apiuserlogin.service.feign.UserLoginClient;
import com.qfedu.fmmall.common.status.ResStatus;
import com.qfedu.fmmall.common.utils.MD5Utils;
import com.qfedu.fmmall.common.vo.ResultVO;
import com.qfedu.fmmall.entity.Users;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;


/**
 * @author : yanBin
 * @date :2022/1/20 15:18
 */
@Service
public class UserLoginServiceImpl implements UserLoginService {
    @Autowired
    private UserLoginClient userLoginClient;

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public ResultVO checkLogin(String username, String password) {
        try {
            List<Users> usersList = userLoginClient.getCheck(username);
            if (usersList == null) {
                return new ResultVO(ResStatus.NO.ordinal(), "没有此用户", null);
            }
            if (usersList.size() <= 0) {
                return new ResultVO(ResStatus.NO.ordinal(), "服务繁忙，请重新访问", null);
            }
            Users user = null;
            for (Users users : usersList) {
                if (MD5Utils.md5(password).equals(user.getPassword())) {
                    user=users;
                    break;
                }
            }
            if (user == null){
                return new ResultVO(ResStatus.NO.ordinal(), "密码错误", null);
            }
            //        用Base64Utils生成token字符串，但是规则太简单不适用
//        String token = Base64Utils.encode(username + password + new Date() + 123456);
//        用jwt生成token字符串
            HashMap<String, Object> map = new HashMap<>();
            map.put("key1", "value1");
            map.put("key2", "value2");
            JwtBuilder builder = Jwts.builder();
            String token = builder.setSubject(username)    //设置token数据
                    .setIssuedAt(new Date()) //设置开始时间
                    .setId(user.getUserId().toString())//设置用户id
                    .setClaims(map)  //map中可以存放其他数据
                    .setExpiration(new Date(System.currentTimeMillis() + 24 * 60 * 60 * 1000))//过期时间为一天
                    .signWith(SignatureAlgorithm.HS256, "123456") //设置加密方法和加密密码
                    .compact();  //生成字符串
            //把登录信息用token字符串为key存入redis中
            String userJson = objectMapper.writeValueAsString(user);
            stringRedisTemplate.boundValueOps(token).set(userJson, 30, TimeUnit.MINUTES);
            return new ResultVO(ResStatus.OK.getCode(), token, user);

        } catch (Exception e) {
            e.getLocalizedMessage();
            return new ResultVO(ResStatus.NO.ordinal(), "登录失败。", null);
        }

    }
}
